package common;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

/**
 * 网络相关工具方法
 */
public class NetworkUtil {
    private static final Logger logger = LogUtil.getLogger(NetworkUtil.class.getName());

    /**
     * 读取完整的消息
     */
    public static Message readMessage(SocketChannel channel) throws IOException {
        // 读取消息头
        ByteBuffer headerBuffer = ByteBuffer.allocate(Protocol.HEADER_SIZE);

        int bytesRead = 0;
        while (bytesRead < Protocol.HEADER_SIZE) {
            int count = channel.read(headerBuffer);
            if (count < 0) {
                throw new IOException("Connection closed by remote");
            }
            bytesRead += count;
        }

        headerBuffer.flip();

        // 解析头部信息
        byte version = headerBuffer.get();
        byte type = headerBuffer.get();
        int requestId = headerBuffer.getInt();
        int length = headerBuffer.getInt();

        if (length > Protocol.MAX_PACKET_SIZE) {
            throw new IOException("Message too large: " + length);
        }

        // 读取消息体
        ByteBuffer dataBuffer = ByteBuffer.allocate(length);
        bytesRead = 0;

        while (bytesRead < length) {
            int count = channel.read(dataBuffer);
            if (count < 0) {
                throw new IOException("Connection closed by remote");
            }
            bytesRead += count;
        }

        dataBuffer.flip();
        byte[] data = new byte[length];
        dataBuffer.get(data);

        return new Message(type, requestId, data);
    }

    /**
     * 发送完整的消息
     */
    public static void writeMessage(SocketChannel channel, Message message) throws IOException {
        ByteBuffer buffer = message.encode();

        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
    }
}
